package com.cetc.sdp.mzga.service.conn;

import java.sql.Connection;

import org.jooq.Configuration;
import org.jooq.DSLContext;
import org.jooq.SQLDialect;
import org.jooq.conf.Settings;
import org.jooq.impl.DSL;
import org.jooq.impl.DefaultConfiguration;

import com.cetc.sdp.mzga.service.inter.Callable;

public class PhoenixContext {
  private static Settings settings = new Settings();
    
  static {
    settings.setExecuteLogging(true);
    settings.withRenderFormatted(true);
  }
  
  public static Object execute(Callable call, boolean autoCommit) 
      throws Exception {
    Object ret = null;
    DSLContext context = null;
    
    Connection conn = DruidPool.getInstance().getHBaseConnection();  
    conn.setAutoCommit(autoCommit);
    Configuration configuration = new DefaultConfiguration().set(conn)
                                                            .set(SQLDialect.MYSQL)      
                                                            .set(settings);
    try {
      context = DSL.using(configuration);
      ret = call.call(context);
    } finally {
      if (null != conn) {
        conn.close();
      }
      
      if (null != context) {
        context.close();
      }
    }

    return ret;
  }
  
  public static Object execute(Callable call) 
      throws Exception {
    return execute(call, false);
  }
   
}
